<template>
  <div class="login_body">
    <div class="bg" />
    <div class="box">
      <div class="title">智慧园区-登录</div>
      <el-form ref="form" :model="userForm" :rules="rules">
        <el-form-item
          label="账号"
          prop="username"
        >
          <el-input v-model="userForm.username" />
        </el-form-item>

        <el-form-item

          label="密码"
          prop="password"
        >
          <el-input
            v-model="userForm.password"
            type="password"
          />
        </el-form-item>

        <el-form-item prop="rember">
          <el-checkbox v-model="userForm.rember">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <!-- 整体校验 -->
          <el-button type="primary" class="login_btn" @click="doLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { FORMDATA_KEY } from '@/constants/KEY'
export default {
  name: 'Login',
  data() {
    return {
      userForm: {
        username: '',
        password: '',
        rember: false
      },
      rules: {
        // 不使用校验器校验
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, validator: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'))
          }
        }, trigger: 'blur' }]

      }
    }
  },
  created() {
    const formdata = JSON.parse(localStorage.getItem(FORMDATA_KEY))
    if (FORMDATA_KEY) {
      this.userForm = {
        ...this.userForm,
        ...formdata
      }
    }
  },
  methods: {
    // 整体校验
    // 坑点：▄█▀█● 需要关注同步和异步问题
    async doLogin() {
      await this.$refs.form.validate((zhi) => {
        if (!zhi) {
          return false
        }
      })
      await this.$store.dispatch('user/doLogin', this.userForm)
      // 登录成功，判断需不需要记住账号和密码 （ls实现，后端是不需要账号和密码的）
      if (this.userForm.rember) {
        localStorage.setItem(FORMDATA_KEY, JSON.stringify({ username: this.userForm.username, password: this.userForm.password }))
      } else {
        // 清空已经记住的账号和密码
        localStorage.removeItem(FORMDATA_KEY)
      }
      this.$router.push('/')
    }
  }
}

</script>

<style scoped lang="scss">
  .login_body {
    display: flex;
  }
  .bg {
    width: 60vw;
    height: 100vh;
    background: url('~@/assets/login-bg.svg') no-repeat;
    background-position: right top;
    background-size: cover;
  }
  .box {
    margin: 200px 10% 0;
    flex: 1;
    .title {
      padding-bottom: 76px;
      font-size: 26px;
      font-weight: 500;
      color: #1e2023;
    }
    ::v-deep() {
      .ant-form-item {
        display: flex;
        margin-bottom: 62px;
        flex-direction: column;
      }
      .ant-form-item-label label {
        font-size: 16px;
        color: #8b929d;
      }
      .ant-input,
      .ant-input-password {
        border-radius: 8px;
      }
    }
  }
  .login_btn{
    width: 100%;
  }
</style>
